import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../api/dynamic_service.dart';
import 'package:home_framework/models/dynamic_entity.dart';

class DynamicModel with ChangeNotifier {
  List<DynamicEntity> _dynamics = [];
  DynamicEntity _currentDynamic;
  int _currentPage = 1;
  final int _pageSize = 20;

  List<DynamicEntity> get dynamics => _dynamics;
  DynamicEntity get currentDynamic => _currentDynamic;

  void refresh() {
    _currentPage = 1;
    _requestNewItems();
  }

  void load() {
    _currentPage += 1;
    _requestNewItems();
  }

  void _requestNewItems() async {
    var response = await DynamicService.list(_currentPage, _pageSize);
    if (response != null && response.statusCode == 200) {
      List<dynamic> _jsonItems = response.data;
      List<DynamicEntity> _newItems =
          _jsonItems.map((json) => DynamicEntity.fromJson(json)).toList();
      if (_currentPage == 1) {
        _dynamics = _newItems;
      } else {
        _dynamics += _newItems;
      }
    }

    notifyListeners();
  }

  void removeWithId(String id) async {
    var response = await DynamicService.delete(id);
    if (response?.statusCode == 200) {
      _dynamics.removeWhere((element) => element.id == id);
      notifyListeners();
    } else {
      EasyLoading.showError(response?.statusMessage ?? '删除失败');
    }
  }

  Future<bool> getDynamic(String id) async {
    EasyLoading.showInfo('加载中...', maskType: EasyLoadingMaskType.black);
    if (_currentDynamic?.id != id) {
      _currentDynamic = null;
    }
    var response = await DynamicService.get(id);
    if (response != null && response.statusCode == 200) {
      _currentDynamic = DynamicEntity.fromJson(response.data);
      notifyListeners();

      EasyLoading.dismiss();
      return true;
    } else {
      EasyLoading.showInfo(response?.statusMessage ?? '请求失败');
      return false;
    }
  }

  void updateViewCount(String id) async {
    var response = await DynamicService.updateViewCount(id);
    if (response != null && response.statusCode == 200) {
      _currentDynamic.viewCount = response.data['viewCount'];
      // 如果元素在列表中，则更新
      int currentIndex =
          dynamics.indexWhere((element) => element.id == _currentDynamic.id);
      if (currentIndex != -1) {
        _dynamics[currentIndex] = _currentDynamic;
        notifyListeners();
      }
    }
  }

  void add(DynamicEntity newDynamic) {
    _dynamics.insert(0, newDynamic);
    notifyListeners();
  }

  void update(DynamicEntity newDynamic) {
    int currentIndex =
        dynamics.indexWhere((element) => element.id == newDynamic.id);
    if (currentIndex != -1) {
      _dynamics[currentIndex] = newDynamic;
      notifyListeners();
    }
  }
}
